package com.szewec.ps.ui.project;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.Constants;
import com.szewec.ps.base.Enums;
import com.szewec.ps.databinding.ActivityProjectEditBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.ViewModeValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.project.ProjectMemberListModel;
import com.szewec.ps.model.project.SelectUserModel;
import com.szewec.ps.model.user.UserModel;
import com.szewec.ps.myinterface.IUserInfo;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.ui.member.MemberSelectActivity;
import com.szewec.ps.ui.tabbar.ApplicationFragment;
import com.szewec.ps.ui.tabbar.HomePageActivity;
import com.szewec.ps.util.CommonUtils;
import com.szewec.ps.util.OneOffCupboard;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.StringUtils;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.content.ContentValues.TAG;

public class ProjectEditActivity extends BaseActivity {
    private ActivityProjectEditBinding _binding;
    private LoadingDialog _loadingDialog;

    private String ModeFlag_Add_Edit_View; //标志当前界面是详情模式，还是新增模式，还是编辑模式!
    private ProjectListModel.ProjectModel _itemModel = new ProjectListModel.ProjectModel();

    private List<? extends IUserInfo> _selectedProjectChargeList = new ArrayList<>();
    private List<? extends IUserInfo> _selectedProjectMemberList = new ArrayList<>();
    private Enums.ProjTypeGrade1 _selectedProjTypeGrade1Enum;
    private Enums.ProjTypeGrade2 _selectedProjTypeGrade2Enum;

    private void setSelectedProjectTypeEnum(Enums.ProjTypeGrade1 grade1, Enums.ProjTypeGrade2 grade2){
        if (grade1 == null || grade2 == null){
            return;
        }

        _selectedProjTypeGrade1Enum = grade1;
        _selectedProjTypeGrade2Enum = grade2;
        _binding.projectType.setValue(grade1.getValue() + " " + grade2.getValue());
    }

    private void setProjectChargeListList(List<? extends IUserInfo> list) {
        if (list == null){
            return;
        }
        _binding.projectCharge.setValue(StringUtils.getStrWithList(",", list, IUserInfo::getUserName));
        _selectedProjectChargeList = list;
    }

    private void setProjectMemberList(List<? extends IUserInfo> list) {
        if (list == null){
            return;
        }
        _binding.projectMember.setValue(StringUtils.getStrWithList(",", list, IUserInfo::getUserName));
        _selectedProjectMemberList = list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        _binding = DataBindingUtil.setContentView(this, R.layout.activity_project_edit);
        ButterKnife.bind(this);
        _loadingDialog = LoadingDialog.getInstance(this);

        initData();

        initTitleBar();

        initDataToView();
    }

    private void initData(){
        PresentValue<ProjectListModel.ProjectModel> presentValue = (PresentValue<ProjectListModel.ProjectModel>) getIntent().getSerializableExtra(Constants.PRESENT_VALUE);
        //获取是新增还是修改还是详情展示
        ModeFlag_Add_Edit_View = presentValue.getFlag();
        _itemModel = presentValue.getT();
    }

    private void initTitleBar(){
        ViewModeValue viewModeValue = new ViewModeValue(this, ModeFlag_Add_Edit_View, _binding.titleBar, _binding.llContainer);

        //设置导航栏右侧按钮
        if (Constants.PRESENT_VALUE_FLAG.VIEW.equals(ModeFlag_Add_Edit_View)){//详情预览
            CommonUtils.setViewMode(viewModeValue, this::finish, this::callMoreMenu);
            _binding.titleBar.setTitle("项目详情");
        }
        else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(ModeFlag_Add_Edit_View)){
            CommonUtils.setViewMode(viewModeValue, this::returnCheck, this::appendOrModifyData);
            _binding.titleBar.setTitle("新建项目");
        }
        else if (Constants.PRESENT_VALUE_FLAG.EDIT.equals(ModeFlag_Add_Edit_View)){
            CommonUtils.setViewMode(viewModeValue, this::returnCheck, this::appendOrModifyData);
            _binding.titleBar.setTitle("项目编辑");
        }
    }

    private void initDataToView(){
        //新增模式
        if(Constants.PRESENT_VALUE_FLAG.ADD.equals(ModeFlag_Add_Edit_View)){
            Log.i(TAG, "The add mode we should do nothing.");
        }
        //编辑/预览模式
        else {
            _binding.projectCode.setValue(_itemModel.getProjectCode());
            _binding.projectName.setValue(_itemModel.getProjectName());
            _binding.projectType.setValue(Enums.ProjTypeGrade1.getValueByKey(_itemModel.getProjectTypeGrade1()) + " " + Enums.ProjTypeGrade2.getValueByKey(_itemModel.getProjectTypeGrade2()));
            _binding.projectDesc.setValue(_itemModel.getProjectDesc());
            _binding.researchArea.setValue(_itemModel.getResearchArea());
            _binding.projectCharge.setValue(StringUtils.getStrWithList(",", _itemModel.getProjectChargeList(), ProjectMemberListModel.ProjectMemberModel::getMemberUserName));
            _binding.projectMember.setValue(StringUtils.getStrWithList(",", _itemModel.getProjectMemberList(), ProjectMemberListModel.ProjectMemberModel::getMemberUserName));

            //设置选中数据源头
            _selectedProjTypeGrade1Enum = Enums.ProjTypeGrade1.getEnumByKey(_itemModel.getProjectTypeGrade1());
            _selectedProjTypeGrade2Enum = Enums.ProjTypeGrade2.getEnumByKey(_itemModel.getProjectTypeGrade2());
            _selectedProjectMemberList = _itemModel.getProjectMemberList();
            _selectedProjectChargeList = _itemModel.getProjectChargeList();
        }
    }

    private void appendOrModifyData() {

        String projectCode = _binding.projectCode.getStringValue();
        String projectName = _binding.projectName.getStringValue();

        if (projectCode == null
                || projectName == null
                || _selectedProjTypeGrade1Enum ==null
                || _selectedProjTypeGrade2Enum == null ){
            BamToast.showText(this, "必填字段不能为空");
            return;
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("projectCode", projectCode);
        paramMap.put("projectName", projectName);
        paramMap.put("projectTypeGrade1", _selectedProjTypeGrade1Enum.getKey());
        paramMap.put("projectTypeGrade2", _selectedProjTypeGrade2Enum.getKey());
        paramMap.put("projectDesc", _binding.projectDesc.getStringValue());
        paramMap.put("researchArea", _binding.researchArea.getStringValue());

        if ( _selectedProjectMemberList == null || _selectedProjectMemberList.size() == 0 ){
            BamToast.showText(this, "项目成员不能为空");
            return;
        }

        String companyId = (String) SharedPreferencesUtil.getData(PreferincesContext.COMPANY_ID,"");
        List<ProjectMemberListModel.ProjectMemberModel> memberList = new ArrayList<>();
        for ( IUserInfo model : _selectedProjectMemberList ){
            ProjectMemberListModel.ProjectMemberModel obj = new ProjectMemberListModel.ProjectMemberModel();
            obj.setMemberUserId(model.getUserId());
            obj.setMemberUserName(model.getUserName());
            obj.setIsProjCharge(Enums.ProjectMemberTypeEnum.项目成员.getKey());
            obj.setCompanyId(companyId);
            memberList.add(obj);
        }

        List<ProjectMemberListModel.ProjectMemberModel> chargeList = new ArrayList<>();
        for ( IUserInfo model : _selectedProjectChargeList ){
            ProjectMemberListModel.ProjectMemberModel obj = new ProjectMemberListModel.ProjectMemberModel();
            obj.setMemberUserId(model.getUserId());
            obj.setMemberUserName(model.getUserName());
            obj.setIsProjCharge(Enums.ProjectMemberTypeEnum.项目负责人.getKey());
            obj.setCompanyId(companyId);
            chargeList.add(obj);
        }

        paramMap.put("projectMemberList", memberList);
        paramMap.put("projectChargeList", chargeList);


        //编辑模式
        if(Constants.PRESENT_VALUE_FLAG.EDIT.equals(ModeFlag_Add_Edit_View)){
            paramMap.put("id", _itemModel.getId());
            OkHttp.post("/tpms-plan-service/api/project/update", paramMap, (result -> {
                Log.i(TAG, "update project result is：" + result);

                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = (String) jsonObject.get("code");

                if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))){
                    Object msg = jsonObject.get("msg");
                    BamToast.showText(this, "请求错误：" + msg);
                    return;
                }

                BamToast.showText(this, "修改成功");
                setResult(RESULT_OK, new Intent());
                startActivity(new Intent(ProjectEditActivity.this, HomePageActivity.class));
            }));
        }
        //新增模式
        else if (Constants.PRESENT_VALUE_FLAG.ADD.equals(ModeFlag_Add_Edit_View)){
            OkHttp.post("/tpms-plan-service/api/project/create", paramMap, (result -> {
                Log.i(TAG, "create project result is：" + result);

                JSONObject jsonObject = JSONObject.parseObject(result);
                String code = (String) jsonObject.get("code");
                assert code != null;

                if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))){
                    Object msg = jsonObject.get("msg");
                    BamToast.showText(this, "请求错误：" + msg);
                    return;
                }

                BamToast.showText(this, "新增成功");
                setResult(RESULT_OK, new Intent());
                finish();
            }));
        }
        //
        else {
            BamToast.showText(this, "未知错误");
        }
    }

    private void deleteData(){
        OkHttp.post("/tpms-plan-service/api/project/delete/" + _itemModel.getId(), new HashMap<>(), (result -> {
            Log.i(TAG, "delete project result is：" + result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String code = (String) jsonObject.get("code");
            assert code != null;

            if (!Enums.ResponseCodeEnum.请求成功.getKey().equals(Integer.valueOf(code))){
                Object msg = jsonObject.get("msg");
                BamToast.showText(this, "请求错误：" + msg);
                return;
            }

            BamToast.showText(this, "删除成功");
            setResult(RESULT_OK, new Intent());
            finish();
        }));
    }

    private void returnCheck(){
        finish();
    }

    private void callMoreMenu(){
        CommonUtils.showMoreMenu(this, _binding.titleBar.getRightLayout(), this::linkToEditActivity, this::deleteData);
    }

    private void linkToEditActivity() {
        Intent intent = new Intent(this, ProjectEditActivity.class);
        PresentValue<ProjectListModel.ProjectModel> presentValue = new PresentValue<>(Constants.PRESENT_VALUE_FLAG.EDIT, _itemModel);
        intent.putExtra(Constants.PRESENT_VALUE, presentValue);
        startActivity(intent);
    }



    @OnClick({R.id.project_Type,R.id.project_Charge,R.id.project_Member})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.project_Type: {
                //项目类型
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK){
                            Enums.ProjTypeGrade1 grade1Enum = (Enums.ProjTypeGrade1)OneOffCupboard.sharedInstance().getThenRemove(ProjectTypeActivity.KEY_SELECTED_PROJTYPE_GRADE1);
                            Enums.ProjTypeGrade2 grade2Enum = (Enums.ProjTypeGrade2)OneOffCupboard.sharedInstance().getThenRemove(ProjectTypeActivity.KEY_SELECTED_PROJTYPE_GRADE2);
                            setSelectedProjectTypeEnum(grade1Enum, grade2Enum);
                        }
                    }
                }).launch(new Intent(this,ProjectTypeActivity.class));

                break;
            }
            case R.id.project_Charge: {

                Intent intent = new Intent(this, MemberSelectActivity.class);
                PresentValue<List<? extends IUserInfo>> presentValue = new PresentValue<>(MemberSelectActivity.SELECTED_MEMBERS_KEY, _selectedProjectChargeList);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);

                //项目负责人
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK){
                            List<SelectUserModel> selectedArr = (List<SelectUserModel>)OneOffCupboard.sharedInstance().getThenRemove(MemberSelectActivity.SELECTED_MEMBERS_KEY);
                            setProjectChargeListList(selectedArr);
                        }
                    }
                }).launch(intent);

                break;
            }
            case R.id.project_Member: {

                Intent intent = new Intent(this, MemberSelectActivity.class);
                PresentValue<List<? extends IUserInfo>> presentValue = new PresentValue<>(MemberSelectActivity.SELECTED_MEMBERS_KEY, _selectedProjectMemberList);
                intent.putExtra(Constants.PRESENT_VALUE, presentValue);

                //项目成员
                registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK){
                            List<SelectUserModel> selectedArr = (List<SelectUserModel>)OneOffCupboard.sharedInstance().getThenRemove(MemberSelectActivity.SELECTED_MEMBERS_KEY);
                            setProjectMemberList(selectedArr);
                        }
                    }
                }).launch(intent);

                break;
            }
        }
    }
}
